package org.tomcat.unit501;

import javax.servlet.ServletException;
import java.io.IOException;

public class SimplePipeline implements Pipeline, Contained {

    protected Valve basic = null;

    protected Container container = null;

    protected String info = "org.tomcat.unit5.SimplePipeline/1.0";

    protected boolean started = false;

    protected Valve valves[] = new Valve[0];

    public SimplePipeline() {
        this(null);
    }

    public SimplePipeline(Container container) {
        setContainer(container);
    }

    @Override
    public Valve getBasic() {
        return this.basic;
    }

    @Override
    public void setBasic(Valve valve) {
        this.basic = valve;
    }

    @Override
    public void addValve(Valve valve) {
        synchronized (valves) {
            Valve results[] = new Valve[valves.length +1];
            System.arraycopy(valves, 0, results, 0, valves.length);
            results[valves.length] = valve;
            this.valves = results;
        }
    }

    @Override
    public Valve[] getValves() {
        return new Valve[0];
    }

    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {
        (new StandardValveContext()).invokeNext(request, response);
    }

    @Override
    public void removeValve(Valve valve) {

    }

    @Override
    public Container getContainer() {
        return null;
    }

    @Override
    public void setContainer(Container container) {

    }

    protected class StandardValveContext implements ValveContext {
        protected int stage = 0;

        private String info;

        @Override
        public String getInfo() {
            return info;
        }

        @Override
        public void invokeNext(Request request, Response response) throws IOException, ServletException {
            int subscript = stage;
            stage = stage + 1;
            if (subscript < valves.length) {
                valves[subscript].invoke(request, response, this);
            } else if ((subscript == valves.length) && (basic != null)) {
                basic.invoke(request, response, this);
            } else {
                throw new ServletException("standardPipeline.noValue");
            }
        }

    }
}
